import { Injectable, ConflictException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Favorite } from './entities/favorite.entity';

/**
 * 收藏服务
 */
@Injectable()
export class FavoritesService {
  constructor(
    @InjectRepository(Favorite)
    private favoritesRepository: Repository<Favorite>,
  ) {}

  /**
   * 添加收藏
   */
  async add(userId: number, toolId: number): Promise<Favorite> {
    // 检查是否已收藏
    const existing = await this.favoritesRepository.findOne({
      where: { userId, toolId },
    });

    if (existing) {
      throw new ConflictException('已经收藏过该工具');
    }

    const favorite = this.favoritesRepository.create({ userId, toolId });
    return await this.favoritesRepository.save(favorite);
  }

  /**
   * 取消收藏
   */
  async remove(userId: number, toolId: number): Promise<void> {
    const favorite = await this.favoritesRepository.findOne({
      where: { userId, toolId },
    });

    if (!favorite) {
      throw new NotFoundException('未找到收藏记录');
    }

    await this.favoritesRepository.remove(favorite);
  }

  /**
   * 获取用户的收藏列表
   */
  async findByUser(userId: number): Promise<Favorite[]> {
    return await this.favoritesRepository.find({
      where: { userId },
      relations: ['tool', 'tool.category', 'tool.tags'],
      order: { createdAt: 'DESC' },
    });
  }

  /**
   * 检查是否已收藏
   */
  async isFavorited(userId: number, toolId: number): Promise<boolean> {
    const favorite = await this.favoritesRepository.findOne({
      where: { userId, toolId },
    });
    return !!favorite;
  }
}





